/*
 * Unit Test for yasa
 * $Id: testyasa.c 2 2008-10-25 08:17:21Z clsung $
 */
#include "suffix.h"
#include "mmap.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "CUnit/Basic.h"

/* Pointer to the file used by the tests. */
const char *inputfilename = NULL;
static char* text_ptr = NULL;
static int min_length = 1;
static int max_length = 40;
extern FILE* debugfile;

/* The suite initialization function.
 * Opens the temporary file used by the tests.
 * Returns zero on success, non-zero otherwise.
 */
int init_suite1(void)
{
    if (NULL == (debugfile = fopen("testlog.txt", "w+"))) {
	return -1;
    }   else {
	return 0;
    }
}

// the change of result mean feature has modified, CAUTION!!!
void testYASAGoldFile(void)
{
    const char *gold_file = "examples/as_test.result.gold";
    int return_val;
    int uflag = 1; // utf-8
    inputfilename = "examples/as_test.utf8";
    char **output = (char **)calloc (1, sizeof(char**));

    text_ptr = mmap_open_file(inputfilename);
    int len = strlen(text_ptr);
    return_val = do_suffix(text_ptr, uflag, max_length, min_length, output);
    mmap_close (text_ptr, len);
    CU_ASSERT(1 == return_val);
    
    text_ptr = mmap_open_file(gold_file);
    CU_ASSERT_STRING_EQUAL(output[0], text_ptr);
    len = strlen(text_ptr);
    mmap_close (text_ptr, len);
    free ((char**)output);
}

void testYASAGeneral(void)
{
    char *text = "I come from a little world, trying to save the world ok?";
    int return_val;
    int uflag = 0;
    char **output = (char **)calloc (1, sizeof(char**));

    // Test 1
    return_val = do_suffix(text, uflag, max_length, min_length, output);
    CU_ASSERT(1 == return_val);
    CU_ASSERT(0 == strcmp("world\t2\n", output[0]));
    CU_ASSERT_STRING_EQUAL(output[0], "world\t2\n");

    // Test 2
    text = "A B B A A B B A C";
    char *expect = "A B B A\t2\n";
    return_val = do_suffix(text, uflag, max_length, min_length + 1, output);
    CU_ASSERT(1 == return_val);
    CU_ASSERT(0 == strncmp(expect, output[0], strlen(expect)));
    free ((char**)output);
}

int clean_suite1(void)
{
    if (0 != fclose(debugfile)) {
	return -1;
    }   else {
	debugfile = NULL;
	return 0;
    }
} 
int main (int argc, const char **argv)
{
    CU_pSuite pSuite = NULL;

    if (argc > 0) 
	inputfilename = argv[0];
    /* initialize the CUnit test registry */
    if (CUE_SUCCESS != CU_initialize_registry())
	return CU_get_error();

    /* add a suite to the registry */
    pSuite = CU_add_suite("Suite_1", init_suite1, clean_suite1);
    if (NULL == pSuite) {
	CU_cleanup_registry();
	return CU_get_error();
    }

    /* add the tests to the suite */
    CU_add_test(pSuite, "test of gold standard yasa()", testYASAGoldFile);
    CU_add_test(pSuite, "test of english yasa()", testYASAGeneral);

    /* Run all tests using the CUnit Basic interface */
    CU_basic_set_mode(CU_BRM_VERBOSE);
    CU_basic_run_tests();
    CU_cleanup_registry();
    return CU_get_error();
}
